<!--
 * @Author: Wushiqi
 * @Descripttion: 手写new
 * @Date: 2021-04-23 16:10:48
 * @LastEditor: Wushiqi
 * @LastEditTime: 2021-04-27 11:35:07
-->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    // new
    function myNew(fn) {
      // 创建一个空对象
      let obj = {}
      // 让新对象的隐式原型__proto__指向原对象的显式原型prototype
      obj.__proto__ = fn.prototype
      // 将构造函数的作用域赋值(call和apply都行)给新对象，即this指向这个新对象
      const res = fn.call(obj)
      console.log(res); // undefined
      console.log(obj); // Stu {name: "na342me"}
      // 判断函数执行有没有返回其他对象，如果有就返回其他对象，如果没有就返回新对象
      if (typeof res === 'object' || typeof res === 'function') {
        return res
      }
      return obj
    }
    const Stu = function() {
      this.name = 'na342me'
    }
    const stu = myNew(Stu)
    console.log(stu.name); // na342me
  </script>
</body>
</html>